// ignore_for_file: constant_identifier_names

import 'dart:io';

import 'package:dart_bean/setting.dart';
import 'package:dart_style/dart_style.dart';

const bool kReleaseMode = bool.fromEnvironment('dart.vm.product');
final String separator = Platform.isWindows ? r'\' : '/';

extension RegExpExt on RegExp {
  RegExp fixNamedGroup([Map<String, dynamic>? map]) {
    var c = pattern;
    map?.forEach((key, value) {
      c = c.replaceAll(key, value.toString());
    });
    c = c.replaceAll('(@<', '(?<');
    return RegExp(
      c,
      multiLine: isMultiLine,
      caseSensitive: isCaseSensitive,
      unicode: isUnicode,
      dotAll: isDotAll,
    );
  }
}

extension StringExt on String {
  String lowerFirst() {
    if (length <= 1) return toLowerCase();
    return this[0].toLowerCase() + substring(1);
  }

  String upperFirst() {
    if (length <= 1) return toUpperCase();
    return this[0].toUpperCase() + substring(1);
  }

  String substringAfterLast(Pattern pattern) {
    final start = lastIndexOf(pattern);
    if (start != -1) {
      return substring(start + 1);
    } else {
      return this;
    }
  }

  String fixePathStyle() {
    if (separator != '/') {
      return replaceAll('/', separator);
    } else {
      return this;
    }
  }
}

extension IterableExt<E> on Iterable<E> {
  E? firstOrNull([bool Function(E element)? test]) {
    try {
      if (test != null) {
        return firstWhere(test);
      } else if (isNotEmpty) {
        return first;
      } else {
        return null;
      }
    } catch (e) {
      return null;
    }
  }

  E? lastOrNull([bool Function(E element)? test]) {
    try {
      if (test != null) {
        return lastWhere(test);
      } else if (isNotEmpty) {
        return last;
      } else {
        return null;
      }
    } catch (e) {
      return null;
    }
  }
}

String getRelativePath(File file, Directory toDir) {
  if (file.path.startsWith(toDir.path)) {
    return file.path.replaceFirst(toDir.path, '').replaceAll('\\', '/').substring(1);
  } else {
    final reg = RegExp(r'^.[/\\]');
    final from = file.path.replaceFirst(reg, '');
    final to = toDir.path.replaceFirst(reg, '');
    return from.replaceFirst(to, '');
  }
}

void ensureParent(File file) {
  final dir = file.parent;
  if (!dir.existsSync()) dir.createSync(recursive: true);
}

final _formatter = DartFormatter(pageWidth: dartFormatterPageWidth);

typedef SafeDartFormatter = String Function(String code);

String safeDartFormatter(String code) {
  try {
    return _formatter.format(code);
  } catch (e) {
    return code;
  }
}
